import React, { useRef } from 'react';
import axios from 'axios';

import { Socket } from '../../../types/socket';

interface UserData {
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface Message {
  _id: string;
  from: string;
  to: string;
  message: string;
  messageType: string;
  timestamp: Date;
}

interface PhotoProps {
  currentUser: UserData;
  selectedUser: {
    username: string;
    image: string;
  };
  socket: Socket; // 替换 any 类型
  onMessageSent: (message: Message) => void;
}

const Photo: React.FC<PhotoProps> = ({
  currentUser,
  selectedUser,
  socket,
  onMessageSent,
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 处理图片选择
  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }

      // 验证文件大小（限制为5MB，与后端一致）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件大小不能超过5MB');
        return;
      }

      sendImageMessage(file);
    }
  };

  // 发送图片消息
  const sendImageMessage = async (file: File) => {
    if (!socket) return;

    try {
      // 创建FormData用于上传
      const formData = new FormData();
      formData.append('image', file);

      // 使用新的图片审核接口
      const uploadResponse = await axios.post(
        'http://localhost:3001/ysx/chat/image/upload',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );

      // 处理审核结果
      if (uploadResponse.data.code === 0) {
        // 审核通过
        const imageUrl = `http://localhost:3001${uploadResponse.data.data.imageUrl}`;

        // 创建图片消息
        const newMsg: Message = {
          _id: Date.now().toString(),
          from: currentUser.username,
          to: selectedUser.username,
          message: imageUrl,
          messageType: 'image',
          timestamp: new Date(),
        };

        // 通知父组件消息已发送
        onMessageSent(newMsg);

        // 通过Socket发送图片消息
        socket.emit('send_image', {
          from: currentUser.username,
          to: selectedUser.username,
          imageUrl: imageUrl,
          messageType: 'image',
        });
      } else if (uploadResponse.data.code === -2) {
        // 审核不通过
        alert(`图片审核不通过：${uploadResponse.data.msg}`);
      } else if (uploadResponse.data.code === -3) {
        // 需人工审核
        alert(`图片需人工审核：${uploadResponse.data.msg}`);
      } else {
        // 其他错误
        alert('图片上传失败：' + uploadResponse.data.msg);
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      alert('图片上传失败，请重试');
    }
  };

  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  return (
    <>
      <div className="menu-item" onClick={triggerFileSelect}>
        <span className="menu-icon">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
          </svg>
        </span>
        <span className="menu-text">图片</span>
      </div>

      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleImageSelect}
        style={{ display: 'none' }}
      />
    </>
  );
};

export default Photo;
